﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Radiation.Common;

namespace Radiation___IM.Data
{
    public class DatabaseWriter
    {
        private static DatabaseWriter m_inst;

        public static void Init()
        {
            m_inst = new DatabaseWriter();
        }

        public static DatabaseWriter Instance
        {
            get
            {
                return m_inst;
            }
        }

        // dynamic part

        private ManualResetEvent m_event;
        private Queue<File> m_queue;
        private Thread m_write_thread;

        public DatabaseWriter()
        {
            m_event = new ManualResetEvent(false);
            m_queue = new Queue<File>();

            m_write_thread = new Thread(processQueue);
            m_write_thread.Start();
        }

        ~DatabaseWriter()
        {
            try
            {
                m_write_thread.Abort();
            }
            catch (Exception) { }
        }

        public void Queue(File file)
        {
            try
            {
                lock (m_queue)
                {
                    m_queue.Enqueue(file);
                    m_event.Set();
                }
            }
            catch (Exception e)
            {
                Logger.Instance["error"].add("Data.DatabaseWrite.Queue - Failed to queue - " + e.ToString());
            }
        }

        private void processQueue()
        {
            while (true)
            {
                try
                {
                    FileWorker worker = new FileWorker();

                    while (true)
                    {
                        m_event.WaitOne();

                        while (m_queue.Count > 0)
                        {
                            File file;

                            lock (m_queue)
                            {
                                file = m_queue.Dequeue();
                            }

                            worker.processSave(file);
                        }

                        m_event.Reset();
                    }
                }
                catch (Exception e)
                {
                    Logger.Instance["error"].add("Data.DatabaseWrite.processQueue - Error occured - " + e.ToString());
                    m_event.Reset();
                }
            }
        }

    }
}
